package com.wswy.wzcx.module.base

import android.arch.lifecycle.ViewModel
import android.arch.lifecycle.ViewModelProviders
import android.os.Bundle
import android.support.annotation.Keep
import android.support.v4.util.SparseArrayCompat
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.che.libcommon.ui.BaseFragment
import com.che.libcommon.ui.loading.LoadingFragment
import com.che.libcommon.utils.ToastUtils
import com.wswy.wzcx.model.core.EventNormal
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

abstract class CBaseLoadingFragment : LoadingFragment() {

    protected fun <T: ViewModel> provideViewModel(modelClass:Class<T>):T{
        return ViewModelProviders.of(this).get(modelClass)
    }

    protected fun <T: ViewModel> provideViewModelFromActivity(modelClass:Class<T>):T{
        return ViewModelProviders.of(activity!!).get(modelClass)
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        if (getContentLayoutId() != 0){
            return inflater.inflate(getContentLayoutId(),container,false)
        }
        return super.onCreateView(inflater, container, savedInstanceState)
    }

    open protected fun getContentLayoutId() : Int = 0



    private lateinit var events : SparseArrayCompat<((Any?) -> Unit)>

    @Keep
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventCodeNormal(event: EventNormal){
        if(this::events.isInitialized){
            events.get(event.code)?.invoke(event.code)
        }
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)


        if (!EventBus.getDefault().isRegistered(this)){
            EventBus.getDefault().register(this)
        }

    }

    override fun onDestroy() {
        super.onDestroy()
        if (EventBus.getDefault().isRegistered(this)){
            EventBus.getDefault().unregister(this)
        }
    }

    fun registerEvent(code:Int,callback:((Any?)->Unit)?){
        if (!this::events.isInitialized){
            events = SparseArrayCompat()
        }
        events.put(code,callback)
    }
}